#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <ctime>

int main( int argc, char** argv ) {
	char* windowName = "Camera Display - Recording!";
	cvNamedWindow( windowName, CV_WINDOW_AUTOSIZE );
	//CvCapture* capture = cvCreateFileCapture( argv[2] );
	CvCapture* capture = cvCreateCameraCapture(1);
	//-1: dialog in Windows
	if (!capture){
        return -1;
    }
	IplImage* frame;
	
	double fps = cvGetCaptureProperty (
									   capture,
									   CV_CAP_PROP_FPS
									   );
	//problem with fps for camera!
	
	//hack?
	
	fps = 30;
	
	
	printf("fps=%d\n",(int)fps);
	
	int frameWaitTime_ms = int ( 1000 / fps ) ;
	
	printf("milliseconds per frame =%d\n", frameWaitTime_ms);
	
    CvSize size = cvSize(
						 (int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH),
						 (int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT)
						 );
    
    printf("frame (w, h) = (%d, %d)\n",size.width,size.height);
#ifndef NOWRITE
	CvVideoWriter* writer = cvCreateVideoWriter(  // On linux Will only work if you've installed ffmpeg development files correctly, 
												argv[1],                               // otherwise segmentation fault.  Windows probably better.
												//CV_FOURCC('D', 'I', 'B', ' '), //BROKEN!
												CV_FOURCC('I', '4', '2', '0'),
												//0, // apparently works on Windows, but here? OSX : it seems to default to I420
												//CV_FOURCC('F', 'L', 'V', '1'),
												//CV_FOURCC('D','X','5','0'),    
												fps,
												size
												);
#endif
	
	
	IplImage* mod_frame = cvCreateImage(
										 size,
										 IPL_DEPTH_8U,
										 3
										 );
	
	
	printf("PRESS ANY KEY TO START RECORDING\n");
	
	int frameCount = 0;
	time_t startTime;
	
	cvWaitKey(0);

	startTime = time (NULL);
	
	while(1) {
		frameCount++;
		frame = cvQueryFrame( capture );
		if( !frame ) break;
		cvConvertImage(   //We never make use of this gray image
					   frame,
					   mod_frame,
					   0
					   );
		cvShowImage( windowName, mod_frame );
#ifndef NOWRITE
		cvWriteToAVI( writer, mod_frame );
#endif
		char c = cvWaitKey(33);
		if( c != -1 ) break;
	}
	
	time_t endTime;
	
	endTime = time (NULL);
	
	int elapsedTime = endTime - startTime;
	
	int avgFPS;
	
	if (elapsedTime != 0) {
		avgFPS = frameCount / elapsedTime;
	} else {
		avgFPS = -1;
	}
	
	printf("Avg fps =%d\n", avgFPS);
	
	
#ifndef NOWRITE
    cvReleaseVideoWriter( &writer );
#endif
	cvReleaseCapture( &capture );
	cvDestroyWindow( windowName );
}
